#include <Arduino.h>
#include <BfButton.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>


String endpoint = "Lamp IP";  // something like http://192.168.1.10/
const char * wifi_ssid = "your wifi ssid";
const char * wifi_password = "your wifi password";


unsigned long now = millis();
unsigned long lastTrigger = 0;
unsigned long now2 = millis();
unsigned long lastTrigger2 = 0;
boolean startTimer = false;
int interval = 250; //250ms
int wakeInterval = 8000; //8s
String webpage = "";

int encoderPinA[2] = {5,14};
int encoderPinB[2] = {4,12};
//int encoderPinA = 5;
//int encoderPinB = 4;
//int buttonPin[2] = {D3,D7};

int lastEncoderValue[2] = {0,0};
byte state[2] = {0,0}; // used to read the encoder
volatile int encoder[2] = {0,0};
int bump[] = {0, 0, -1, 1};

ESP8266WiFiMulti WiFiMulti;
BfButton lightButton(BfButton::STANDALONE_DIGITAL, 13, true, LOW);


void pressHandler (BfButton *lightButton, BfButton::press_pattern_t pattern) 
{
	switch (pattern)  {
    case BfButton::SINGLE_PRESS:
//      Serial.println(" pressed.");
      sendRequest("?f1&");
      lastTrigger2 = millis();
      break;
//    case BfButton::DOUBLE_PRESS:
//      Serial.println(" double pressed.");
//      break;
    case BfButton::LONG_PRESS:
//      Serial.println(" long pressed.");
      sendRequest("?f3&");
      lastTrigger2 = millis();
      break;
	}
}

ICACHE_RAM_ATTR void readEncoder(int encoderNum)
{
	startTimer = true;
  lastTrigger = millis();
  int i = encoderNum;
	state[i] = 0;                                // start with 0
	state[i] = state[i] + digitalRead(encoderPinA[i]); // add the state of pin A
	state[i] <<= 1;                              // shift left
	state[i] = state[i] + digitalRead(encoderPinB[i]); // add the state of pin B
	if (state[i] == 0)
	return;                        // ignore this value - keybounce
	encoder[i] = encoder[i] + bump[state[i]]; // added direction of turn to state
	if (encoder[i] <= -99)
	encoder[i] = -99; // lower limit
	if (encoder[i] > 99)
	encoder[i] = 100; // upper limit

}

ICACHE_RAM_ATTR void updateEncoder()
{
  readEncoder(0);
//  Serial.printf("Rot: %d\n", "en0", encoder[0], "en1" ,encoder[1]);
//	Serial.print("en0:");
//	Serial.println(encoder[0]);
//  Serial.flush();
}
ICACHE_RAM_ATTR void updateEncoder2()
{
  readEncoder(1);
/*  startTimer = true;
  lastTrigger = millis();
  int i = 1;
	  state[i] = 0;                                // start with 0
	  state[i] = state[i] + digitalRead(encoderPinA[i]); // add the state of pin A
	  state[i] <<= 1;                              // shift left
	  state[i] = state[i] + digitalRead(encoderPinB[i]); // add the state of pin B
	  if (state[i] == 0)
		return;                        // ignore this value - keybounce
	  encoder[i] = encoder[i] + bump[state[i]]; // added direction of turn to state
	  if (encoder[i] <= -99)
		encoder[i] = -99; // lower limit
	  if (encoder[i] > 99)
		encoder[i] = 100; // upper limit
*/
//  Serial.printf("Rot: %d\n", "en0", encoder[0], "en1" ,encoder[1]);
//	Serial.print("en1:");
//	Serial.println(encoder[1]);	
//  Serial.flush();
}
void sendRequest(String value)
{
  if ((WiFiMulti.run() == WL_CONNECTED))
  {

    WiFiClient client;

    HTTPClient http;

    Serial.print("[HTTP] begin...\n");
    if (http.begin(client, endpoint + value))
    {
      Serial.print("[HTTP] GET...\n");
      int httpCode = http.GET();
      if (httpCode > 0)
      {
        Serial.printf("[HTTP] GET... code: %d\n", httpCode);
        if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY)
        {
//          String payload = http.getString();
          webpage =  http.getString();
//          Serial.println(webpage);
		  
        }
      }
      else
      {
        Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
		
      }
      http.end();
    }
    else
    {
      Serial.printf("[HTTP] Unable to connect\n");
	  
    }
  }
    
}

void setup()
{
	
  pinMode(2, OUTPUT);  //LED_BUILTIN
  
  Serial.begin(115200);
  WiFi.begin(wifi_ssid, wifi_password);
  Serial.print("Connecting");
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println();

  Serial.print("Connected, IP address: ");
  Serial.println(WiFi.localIP());
	for(int i=0; i<2; i++ )
	{
		pinMode(encoderPinA[i], INPUT_PULLUP);
		pinMode(encoderPinB[i], INPUT_PULLUP);
	}
	attachInterrupt(digitalPinToInterrupt(encoderPinA[0]), updateEncoder, RISING );
	attachInterrupt(digitalPinToInterrupt(encoderPinA[1]), updateEncoder2, RISING );
	
	lightButton.onPress(pressHandler)
    .onDoublePress(pressHandler)     // default timeout
    .onPressFor(pressHandler, 1300); // custom timeout for 1 second	
	
	lastTrigger2 = millis();
  digitalWrite(2, LOW);
}

void loop()
{
//  if (isButtonPushDown(0))
//  {
//    sendRequest("button");
//  }
	lightButton.read();
	now = millis();	
  if (startTimer && (lastEncoderValue != encoder) && (now - lastTrigger > interval))
  {
//    String getWebpage = sendRequest("");
    sendRequest("");
    String getWebpage = webpage;
    int colorPos = getWebpage.indexOf('色温');
    int brightPos = getWebpage.indexOf('亮度');
    String colorData = getWebpage.substring(colorPos + 23, colorPos + 28);
    String brightData = getWebpage.substring(brightPos + 24, brightPos + 29);
    colorPos = colorData.indexOf('<');
    brightPos = brightData.indexOf('<');
    colorData = colorData.substring(0,colorPos);
    brightData = brightData.substring(0,brightPos);
    Serial.println(colorData);
    Serial.println(brightData);
    int colorValue = colorData.toInt() + + encoder[0];
    if (colorValue > 100)
    { 
      colorValue = 100;
    }
    if (colorValue < 0)
    { 
      colorValue = 0;
    }
    int brightValue = brightData.toInt() + encoder[1];
    if (brightValue > 100)
    {
      brightValue  = 100;
    }
    if (brightValue < 0)
    {
      brightValue  = 0;
    }
    String senddata = "?c" + String(colorValue) + "b" + String(brightValue) +"&";
    Serial.println(senddata);
    sendRequest(String(senddata));
    for(int i=0; i<2; i++ )
    {
      lastEncoderValue[i] = encoder[i] = 0;
    }
    startTimer = false;	
    lastTrigger2 = millis();
  }
  now2 = millis();
  if (now2 - lastTrigger2 > wakeInterval)
  {
	  ESP.deepSleep(0); 
  }
  
}
